package com.tanhua.dubbo.server.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.pojo.Visitors;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

@Service
public class VisitorsApiImpl implements VisitorsApi{
    @Autowired
    private MongoTemplate mongoTemplate;

    private static final String VISITOR_REDIS_KEY = "VISITOR_USER";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    /**
     * 保存访客数据
     *
     * @param userId 我的id
     * @param visitorUserId 访客id
     * @param from 来源
     * @return
     */
    @Override
    public String saveVisitor(Long userId, Long visitorUserId, String from) {
        //校验 3个参数都不能为空
        if (ObjectUtil.isAllNotEmpty(userId,visitorUserId,from)){
            return null;
        }
        //访客用户在今天是否已经记录过,已记录过不在记录

        String today = DateUtil.today();
        System.out.println(today);
        Long minDate = DateUtil.parseDateTime(today + " 00:00:00").getTime();
        System.out.println(minDate);
        Long maxDate = DateUtil.parseDateTime(today + " 23:59:59").getTime();
        System.out.println(maxDate);

        Query query = Query.query(Criteria.where("userId").is(userId).and("visitorUserId").is(visitorUserId)
        .andOperator(Criteria.where("date").gte(minDate),Criteria.where("date").lte(maxDate)));
        long count = this.mongoTemplate.count(query, Visitors.class);
        if (count>0){
            //今天记录过不记录了
            return null;
        }
        Visitors visitors = new Visitors();
        visitors.setFrom(from);
        visitors.setVisitorUserId(visitorUserId);
        visitors.setUserId(userId);
        visitors.setId(ObjectId.get());
        visitors.setDate(System.currentTimeMillis());

        //存储数据
        this.mongoTemplate.save(visitors);
        return visitors.getId().toHexString();

    }
    /**
     * 查询我的访客数据，存在2种情况：
     * 1. 我没有看过我的访客数据，返回前5个访客信息
     * 2. 之前看过我的访客，从上一次查看的时间点往后查询5个访客数据
     *
     * @param userId
     * @return
     */
    @Override
    public List<Visitors> queryMyVisitor(Long userId) {
       //查前5个访客数据，并且记录访问时间
        Long date = Convert.toLong(this.redisTemplate.opsForHash().get(VISITOR_REDIS_KEY, String.valueOf(userId)));
        Pageable pageable = new PageRequest(0,5, Sort.by(Sort.Order.desc("date")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageable);
        if (ObjectUtil.isNotEmpty(date)){
            query.addCriteria(Criteria.where("date").gte(date));
        }
        List<Visitors> visitorsList = this.mongoTemplate.find(query, Visitors.class);

        //查来访用户得分
        for (Visitors visitors : visitorsList) {

            Query queryScore = Query.query(Criteria.where("toUserId")
                    .is(userId).and("userId").is(visitors.getVisitorUserId())
            );
            RecommendUser recommendUser = this.mongoTemplate.findOne(queryScore, RecommendUser.class);
            if(ObjectUtil.isNotEmpty(recommendUser)){
                visitors.setScore(recommendUser.getScore());
            }else {
                //默认得分
                visitors.setScore(90d);
            }
        }
        return visitorsList;
    }
}
